<template>
  <Card title="转化合格供应商">
    <SupplierTabsForm
      v-if="inited"
      ref="supplier-form"
      type="qualified"
      :list="supplierInfoList"
      :data="supplierData" />
    <div class="actions">
      <el-button :loading="loading" :disabled="!inited" @click="handleShowDialog()" type="primary">确认提交</el-button>
      <el-button :loading="loading" :disabled="!inited" @click="handleSave()">暂存</el-button>
      <el-button :loading="loading" @click="handleBack()">取消</el-button>
    </div>
    <ConvertSupplierDialog
      convertType="2"
      :supplier.sync="supplierData.supplierBill"
      :dialogVisible="dialogVisible"
      @handleClose="handleDialogClose" />
  </Card>
</template>
<script>
import SupplierTabsForm from '@/components/supplier/SupplierTabsForm';
import ConvertSupplierDialog from '@/pages/supplier/components/convertSupplierDialog'; // 转化弹窗
import {
  queryStageSupplierDetail,
} from '@/api/supplier/management/pendingApproval'
import {
  querySupplierDetail, // 根据供应商id 查询供应商详情
} from '@/api/supplier/management/qualifiedSupplier';
import { submitSupplierDetail, stagingSupplierDetail } from '@/api/supplier/management/common';
import Dict from '@/mixins/supplier/dict';
import ManageArea from '@/mixins/supplier/manageArea';
import { getInitialFieldsValue, compactObj } from '@/pages/supplier/utils'
import {
  BUSINESS_INFORMATION_FIELDS,
  BASIC_INFORMATION_FIELDS,
  PRODUCTION_INFORMATION_FIELDS,
  PRODUCT_INFORMATION_FIELDS,
  MANAGEMENT_INFORMATION_FIELDS,
  BILLING_INFORMATION_FIELDS,
  BILLING_METHOD_FIELDS,
  FINANCIAL_INFORMATION_FIELDS,
  WARRANTY_INFORMATION_FIELDS,
  REBATE_INFORMATION_FIELDS,
  DELIVERY_INFORMATION_FIELDS,
} from '@/pages/supplier/management/qualifiedSupplier/constants/info'

export default {
  mixins: [Dict, ManageArea],
  components: { SupplierTabsForm, ConvertSupplierDialog },
  data () {
    const { id = 0, processId = 0 } = this.$route.query
    const supplierBill = getInitialFieldsValue([
      BUSINESS_INFORMATION_FIELDS,
      BASIC_INFORMATION_FIELDS,
      PRODUCTION_INFORMATION_FIELDS,
      PRODUCT_INFORMATION_FIELDS,
      MANAGEMENT_INFORMATION_FIELDS,
    ])
    const supplierContractBill = getInitialFieldsValue([
      BILLING_INFORMATION_FIELDS,
      BILLING_METHOD_FIELDS,
      DELIVERY_INFORMATION_FIELDS,
      WARRANTY_INFORMATION_FIELDS,
      REBATE_INFORMATION_FIELDS,
      FINANCIAL_INFORMATION_FIELDS,
    ])
    supplierBill.supplierNatureClassify = 1
    supplierBill.businessContact = ''
    supplierBill.businessContactName = ''
    supplierBill.managementAreaName = ''
    supplierBill.mainCategoryCode = ''
    supplierBill.mainCategoryId = ''
    supplierBill.supplierClassify = 40332 // 线索>合格
    supplierBill.purchaseStatus = supplierContractBill.purchaseStatus
    supplierBill.stopPurchaseReason = supplierContractBill.stopPurchaseReason
    supplierBill.lastYearPurchaseAmount = supplierContractBill.lastYearPurchaseAmount
    supplierBill.yearPurchaseAmount = supplierContractBill.yearPurchaseAmount
    supplierBill.purchaseAddRatio = supplierContractBill.purchaseAddRatio
    supplierContractBill.warrantyPeriodStandard = supplierBill.warrantyPeriodStandard
    supplierContractBill.warrantyPeriod = supplierBill.warrantyPeriod
    supplierContractBill.qualityCompensation = supplierBill.qualityCompensation
    supplierContractBill.salesSupport = supplierBill.salesSupport
    supplierContractBill.signContract = supplierBill.signContract
    supplierContractBill.cooperativeBrand = ''
    supplierContractBill.cooperativeBrandArr = []
    const supplierCooperationAreaBillList = []
    const supplierCooperativeBrandList = []
    const supplierManageCategoryBillList = []
    const supplierPayeeBillList = []
    const supplierSettlementBillList = []
    const supplierPersonBillList = []
    const supplierPersonOurBillList = []
    const supplierQualificationBillList = []

    return {
      id,
      processId,
      inited: false,
      loading: false,
      dialogVisible: false,
      supplierInfoList: [{
        name: '基本信息',
        children: [{
          name: '工商信息',
          ref: 'business-information-form',
          formFields: BUSINESS_INFORMATION_FIELDS,
          dataSource: 'supplierBill',
          qixinbao: true,
          showMessage: false,
        }, {
          name: '基础信息',
          ref: 'basic-information-form',
          formFields: BASIC_INFORMATION_FIELDS,
          dataSource: 'supplierBill',
        }, {
          name: '生产信息',
          ref: 'production-information-form',
          formFields: PRODUCTION_INFORMATION_FIELDS,
          dataSource: 'supplierBill',
        }]
      }, {
        name: '人员信息',
        children: [{
          ref: 'supplier-staff-list',
          type: 'staffList',
          dataSource: ['supplierPersonBillList', 'supplierPersonOurBillList'],
        }]
      }, {
        name: '商品信息',
        children: [{
          name: '商品信息',
          ref: 'product-information-form',
          formFields: PRODUCT_INFORMATION_FIELDS,
          dataSource: 'supplierBill',
        }],
      }, {
        name: '管理信息',
        children: [{
          name: '管理信息',
          ref: 'management-information-form',
          formFields: MANAGEMENT_INFORMATION_FIELDS,
          dataSource: 'supplierBill',
        }],
      }, {
        name: '合同信息',
        children: [{
          name: '开户行信息',
          ref: 'bank-information-list',
          type: 'bankList',
          dataSource: 'supplierPayeeBillList',
        }, {
          name: '结算信息',
          ref: 'billing-information-form',
          formFields: BILLING_INFORMATION_FIELDS,
          dataSource: 'supplierContractBill',
        }, {
          name: '结算方式',
          ref: 'settlement-method-list',
          type: 'settlementMethod',
          dataSource: 'supplierSettlementBillList',
        }, {
          name: '',
          ref: 'billing-method-form',
          formFields: BILLING_METHOD_FIELDS,
          dataSource: 'supplierContractBill',
        }, {
          name: '财务信息',
          ref: 'financial-information-form',
          formFields: FINANCIAL_INFORMATION_FIELDS.filter(item => {
            return !['contractCode', 'partyA', 'partyB'].includes(item.prop)
          }),
          dataSource: 'supplierContractBill',
        }, {
          name: '铺底质保信息',
          ref: 'warranty-information-form',
          formFields: WARRANTY_INFORMATION_FIELDS,
          dataSource: 'supplierContractBill',
        }, {
          name: '返利信息',
          ref: 'rebate-information-form',
          formFields: REBATE_INFORMATION_FIELDS,
          dataSource: 'supplierContractBill',
        }, {
          name: '交付信息',
          ref: 'delivery-information-form',
          formFields: DELIVERY_INFORMATION_FIELDS,
          dataSource: 'supplierContractBill',
        }],
      }, {
        name: '资质信息',
        children: [{
          name: '资质信息',
          ref: 'qualification-information-list',
          type: 'qualificationList',
          dataSource: 'supplierQualificationBillList',
        }]
      }, {
        name: '考察记录',
        type: 'inspectionRecord',
        id
      }, {
        name: '变更记录',
        type: 'changeRecord',
        id
      }],
      supplierData: {
        supplierBill,
        supplierContractBill,
        supplierCooperationAreaBillList,
        supplierCooperativeBrandList,
        supplierManageCategoryBillList,
        supplierPayeeBillList,
        supplierSettlementBillList,
        supplierPersonBillList,
        supplierPersonOurBillList,
        supplierQualificationBillList,
      },
    }
  },
  created () {
    const { id, processId } = this.$route.query
    if (processId) {
      this.getStageSupplierData(processId)
    } else if (id) {
      this.initSupplierData(id)
    } else {
      this.handleBack()
    }
  },
  methods: {
    // 获取供应商数据
    async initSupplierData (supplierId) {
      const { status, result } = await querySupplierDetail({ supplierId })
      if (status === '0' && result) {
        const userInfo = localStorage.userInfo ? JSON.parse(localStorage.userInfo) : {}
        const { userId = '', userName = '' } = userInfo
        const businessContactInfo = {
          businessContact: userId,
          businessContactName: userName,
        }
        const { supplierCode, supplierId, supplierName } = result.supplier;
        if (result.supplierPayeeList.length == 0) {
          result.supplierPayeeList.push(
            {
              invoiceSupplierName: supplierName,
              invoiceSupplierId: supplierId,
              invoiceSupplierCode: supplierCode,
              payee: supplierName,
            }
          )
        }
        this.setData({
          supplierBill: { ...result.supplier, ...businessContactInfo },
          supplierContractBill: { ...result.supplierContract, rebate: 31 },
          supplierCooperationAreaBillList: result.supplierCooperationAreaList,
          supplierCooperativeBrandList: result.supplierCooperativeBrandList,
          supplierManageCategoryBillList: result.supplierManageCategoryList,
          supplierPayeeBillList: result.supplierPayeeList,
          supplierPersonBillList: result.supplierPersonList,
          supplierPersonOurBillList: result.supplierPersonOurList,
          supplierPersonServiceBillList: result.supplierPersonServiceList,
          supplierQualificationBillList: result.supplierQualificationList,
          supplierSettlementBillList: result.supplierSettlementList,
        })
        this.inited = true
      }
    },
    // 获取暂存数据
    async getStageSupplierData (processId) {
      const { status, result } = await queryStageSupplierDetail({ processId })
      if (status === '0' && result) {
        this.setData(result)
        this.supplierData.processDocumentOperateType = result.processDocumentOperateType
        this.inited = true
      }
    },
    // 初始化表单数据
    setData (data) {
      data = compactObj(data, this.supplierData)
      const {
        supplierBill,
        supplierContractBill,
        supplierManageCategoryBillList,
        supplierPayeeBillList,
        supplierCooperationAreaBillList,
        supplierCooperativeBrandList,
      } = data
      const switchKeys = (keys, key1, key2) => {
        keys.forEach((key) => {
          if (data[key1] && data[key2]) {
            data[key1][key] = data[key2][key]
          }
        })
      }
      switchKeys([
        'warrantyPeriodStandard',
        'warrantyPeriod',
        'qualityCompensation',
        'salesSupport',
        'signContract',
      ], 'supplierBill', 'supplierContractBill')
      switchKeys([
        'purchaseStatus',
        'stopPurchaseReason',
        'lastYearPurchaseAmount',
        'yearPurchaseAmount',
        'purchaseAddRatio',
      ], 'supplierContractBill', 'supplierBill')

      if (supplierBill && supplierBill.businessTerm) {
        const [businessTermStart = '', businessTermEnd = ''] = supplierBill.businessTerm.split(',')
        supplierBill.businessTermStart = businessTermStart
        supplierBill.businessTermEnd = businessTermEnd
      }
      supplierBill.supplierClassify = 40332 // 线索>合格

      // 经营品类
      if (supplierManageCategoryBillList && supplierManageCategoryBillList.length) {
        data.supplierBill.manageCategory = supplierManageCategoryBillList.map((item) => {
          return {
            categoryName: item.manageCategory,
            categoryNo: item.manageCategoryCode,
            categoryUuid: item.manageCategoryId,
          }
        })
      } else {
        data.supplierBill.manageCategory = []
      }

      // 银行数据
      if (supplierPayeeBillList && supplierPayeeBillList.length) {
        data.supplierPayeeBillList.forEach((item) => {
          item.bank = item.bankName || ''
        })
      }

      // 铺底质保金执行区域
      if (supplierContractBill && supplierContractBill.etcQaExecuteArea) {
        data.supplierContractBill.etcQaExecuteAreaArr = supplierContractBill.etcQaExecuteArea.split(',')
      }

      // 合作区域数据
      if (supplierCooperationAreaBillList && supplierCooperationAreaBillList.length) {
        data.supplierContractBill.cooperationArea = supplierCooperationAreaBillList.map(i => i.areaId)
      }

      // 合作品牌数据
      if (supplierCooperativeBrandList && supplierCooperativeBrandList.length) {
        data.supplierContractBill.cooperativeBrand = supplierCooperativeBrandList.map(i => i.brandName).join()
        data.supplierContractBill.cooperativeBrandArr = supplierCooperativeBrandList.map(i => i)
      } else {
        data.supplierContractBill.cooperativeBrand = ''
        data.supplierContractBill.cooperativeBrandArr = []
      }

      // 销售渠道数据
      if (supplierContractBill.salesChannel && supplierContractBill.salesChannel.length) {
        data.supplierContractBill.salesChannelArr = supplierContractBill.salesChannel.split(',').map(i => parseInt(i, 10))
      }

      for (let [k, v] of Object.entries(data)) {
        if (Array.isArray(v)) {
          if (v.length) {
            this.supplierData[k] = v
          }
        } else if (v) {
          this.supplierData[k] = v
        }
      }
    },
    // 显示转化弹窗
    handleShowDialog () {
      this.$refs['supplier-form'].getData(1).then((data) => {
        if (data) {
          this.dialogVisible = true
        }
      })
    },
    // 转化弹窗关闭回调
    handleDialogClose (state) {
      this.dialogVisible = false
      if (state) {
        this.handleSubmit()
      }
    },
    // 提交
    handleSubmit () {
      /**
       * 状态, 1：暂存 10：待审核，20：审核通过，30：审核驳回, 40: 撤回
       */
      /**
       * 1：供应商新增，2：供应商编辑，3：线索转潜在，4：线索转合格，5：潜在转合格，6：加入黑名单，7：移出黑名单
       * ，8：合格降级潜在 9：潜在降级线索，10：淘汰供应商，11：激活供应商，12：运费新增，13：运费编辑  14:考察计划  15:考察报告
       * 16: 潜在供应商新增 17:潜在供应商修改  18:更换业务对接人  19:特殊供应商新增 20:特殊供应商编辑
       */
      const { processId } = this
      let obj = {
        processDocumentStatus: 10,
        processDocumentOperateType: this.supplierData.processDocumentOperateType || 4
      }
      if (processId) {
        obj.processBillId = processId
      }
      // console.log(`processDocumentOperateType: ${obj.processDocumentOperateType}; processDocumentStatus: ${obj.processDocumentStatus}`)
      this.$refs['supplier-form'].getData(1).then((data) => {
        if (data) {
          const { causeType, causeDescription } = this.supplierData.supplierBill
          data.supplierBill.causeType = causeType
          data.supplierBill.causeDescription = causeDescription
          this.editSupplierDetail(Object.assign(obj, data)).catch((reason) => {
            console.log('reason', reason)
            this.loading = false
          })
        }
      })
    },
    // 暂存
    handleSave () {
      const { processId } = this
      let obj = {
        processDocumentStatus: 1,
        processDocumentOperateType: this.supplierData.processDocumentOperateType || 4,
      }
      if (processId) {
        obj.processBillId = processId
      }
      // console.log(`processDocumentOperateType: ${obj.processDocumentOperateType}; processDocumentStatus: ${obj.processDocumentStatus}`)
      this.$refs['supplier-form'].getData().then((data) => {
        if (data) {
          const { managementAreaId, mainCategoryId } = data?.supplierBill || {}
          if (!mainCategoryId) {
            return this.$message.warning('商品信息下的主营品类不能为空')
          }
          if (!managementAreaId) {
            return this.$message.warning('管理信息下的供应商管理区域不能为空')
          }
          this.stagingSupplierDetail(Object.assign(obj, data)).catch((reason) => {
            console.log('reason', reason)
            this.loading = false
          })
        }
      })
    },
    // 编辑供应商
    async editSupplierDetail (data) {
      console.log('editSupplierDetail :>> ', data);
      // return
      this.loading = true;
      const resp = await submitSupplierDetail(data)
      this.loading = false;
      if (resp && resp.status === '0') {
        this.$message.success('保存成功')
        this.handleBack()
      }
    },
    // 暂存供应商
    async stagingSupplierDetail (data) {
      console.log('stagingSupplierDetail :>> ', data);
      // return
      this.loading = true;
      const resp = await stagingSupplierDetail(data)
      this.loading = false;
      if (resp && resp.status === '0') {
        this.$message.success('保存成功')
        this.handleBack()
      }
    },
    handleBack () {
      this.$router.go(-1)
    },
  },
}
</script>
